//gulp的入口文件
const { dest, src, series, parallel, watch } = require("gulp");
const loadPlugins = require("gulp-load-plugins");
const browserSync = require("browser-sync");
const plugin = new loadPlugins();
const bs = browserSync.create();
const del = require("del");

const data = {
  pkg: require("./package.json"),
  date: new Date(),
};
//删除dist文件夹
const clean = () => {
  return del(["dist"]);
};
//样式编译
const style = () => {
  /**
   * 但是并没有与src一样的路径。所以需要指定 {base：'src'}
   */
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugin.sass())
    .pipe(dest("dist"));
};
//脚本编译
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(
      plugin.babel({
        presets: ["@babel/preset-env"],
      })
    )
    .pipe(dest("dist"));
};
// html编译-模板内容替换
const page = () => {
  return src("src/*.html", { base: "src" })
    .pipe(plugin.swig({ data }))
    .pipe(dest("dist"));
};
//图片
const image = () => {
  return src("src/assets/images/**", { base: "src" })
    .pipe(plugin.imagemin())
    .pipe(dest("dist"));
};

const fonts = () => {
  return src("src/assets/fonts/**", { base: "src" })
    .pipe(plugin.imagemin())
    .pipe(dest("dist"));
};
//其他文件
const extra = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"));
};
// 文件引用处理-文件压缩
const useRef = () => {
  return src("dist/*.html", { base: "dist" })
    .pipe(plugin.useref({ searchPath: ["dist", "."] }))
    .pipe(plugin.if(/\.js$/, plugin.uglify()))
    .pipe(plugin.if(/\.css$/, plugin.cleanCss()))
    .pipe(
      plugin.if(
        /\.html$/,
        plugin.htmlmin({
          collapseWhitespace: true,
          minifuCSS: true,
          minifyJS: true,
        })
      )
    )
    .pipe(dest("dist"));
};
//启动服务器浏览器
const serve = () => {
  watch("src/assets/styles/*.scss", style);
  watch("src/assets/scripts/*.js", script);
  watch("src/*.html", page);
  watch(
    ["src/assets/images/**", "src/assets/scripts/*.js", "src/*.html"],
    bs.reload
  );

  bs.init({
    notify: false,
    files: "dist/**",
    server: {
      port: 8080,
      baseDir: ["dist", "public", "src"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};
const compile = parallel(page, script);

//上线之前执行的任务
const build = series(
  clean,
  parallel(series(compile, useRef), fonts, image, extra)
);

const develop = series(compile, serve);

module.exports = {
  clean,
  build,
  develop,
};
